import logging
import os
import sys
import urllib

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from model import *

from seed_getright import SeedGetRight

def _torrentHasFile(torrent, subpath):
    # Single-file torrent matches if subpath is empty:
    if 'length' in torrent.info:
        return len(subpath) == 0
    # Multi-file torrent case:
    for file in torrent.info['files']:
        logging.debug("looking at "+" ".join(file['path']))
        if subpath == file['path']:
            return True
    return False

class FileLookup(SeedGetRight):
    def get(self, path):
        path = urllib.unquote_plus(path)
        logging.debug("looking for "+path)
        p = path.split('/')
        name = p[0]
        subpath = p[1:]
        # We're looking for the first torrent with the right name that
        # contains the right file (if it's a multi-file torrent).
        # And we'll prefer more recent torrents to older ones:
        for torrent in Torrent.gql("WHERE name = :1 ORDER BY date DESC", name):
            if _torrentHasFile(torrent, subpath):
                # Found it, leverage the SeedGetright code to serve it up:
                info_hash = torrent.key().name()
                super(FileLookup, self).get(info_hash, path)
                return
        self.error(404) # Not found

application = webapp.WSGIApplication(
    [
      (r'/files/(.*)', FileLookup) # NOTE: must match the pattern in app.yaml
    ],
    debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
